package org.gpf.dbc;

import java.sql.Connection;
import java.sql.SQLException;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
 * 负责数据库的连接和关闭
 * @author gaopengfei
 * @date 2015-4-23 上午9:15:05
 */
public class DBConnection {

/*	private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
	private static final String DB_URL = "jdbc:mysql://localhost:3306/mldn?characterEncoding=utf8";
	private static final String DB_USER = "root";
	private static final String DB_PASSWORD = "mysqladmin";*/
	
	private Connection conn = null;
	
/*	static{
		try {
			Class.forName(DB_DRIVER);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}*/
	
	public DBConnection() {
		
		/*try {
			conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
		} catch (SQLException e) {
			e.printStackTrace();
		}*/
		
		String DSNAME = "java:comp/env/jdbc/mldn";
		try {
			Context ctx = new InitialContext();
			DataSource ds = (DataSource) ctx.lookup(DSNAME);
			conn = ds.getConnection();
		} catch (NamingException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 数据库的连接
	 */
	public final Connection getConnect(){
		return this.conn;
	}
	
	/**
	 * 数据库的关闭
	 */
	public void close(){
		if (conn!=null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}
